package com.ktwlsoft.fundmanage.controller.sms;

import com.alibaba.fastjson.JSONObject;
import com.ktwlsoft.fundmanage.domain.entity.sms.SendSms;
import com.ktwlsoft.fundmanage.payload.BaseResult;
import com.ktwlsoft.fundmanage.payload.IAccountUser;
import com.ktwlsoft.fundmanage.payload.ResultType;
import com.ktwlsoft.fundmanage.payload.sms.VerificationCodePojo;
import com.ktwlsoft.fundmanage.service.sms.SmsService;
import com.ktwlsoft.fundmanage.utils.MD5;
import com.ktwlsoft.fundmanage.utils.RedisUtil;
import com.ktwlsoft.fundmanage.utils.UserUtils;
import com.ktwlsoft.fundmanage.utils.VerificationCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 验证码控制器
 *
 * @author zhuhe on 2019/5/17 11:21
 * @version 1.0
 */
@Api(value = "验证码控制器", description = "验证码控制器，作者：朱和")
@Controller
@RequestMapping("VerificationCode")
public class VerificationCodeController {

    /** 日志对象 **/
    private static Logger logger = LoggerFactory.getLogger(VerificationCodeController.class);

    /**redis工具*/
    @Autowired
    private RedisUtil redisUtil;

    /**发送短信*/
    @Autowired
    private SmsService smsService;

    /**
      * 获取手机验证码 on 2019/5/17 11:25
      *
      * @return ResponseEntity<Object>
      */
    @ApiOperation(value = "获取手机验证码", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping(value = "getPhoneVerificationCode")
    public ResponseEntity<Object> getVerificationCode(@ApiParam(value = "手机号", name = "phone") @RequestParam(defaultValue = "")String phone) {
        IAccountUser user = UserUtils.getUser();
        if(user.getUserId() == null){
            return ResponseEntity.ok(BaseResult.body(phone, ResultType.BUSINESS_ERROR).withMessage("获取不到当前用户"));
        }
        //获取验证码
        String s = VerificationCodeUtil.getRandomString();
        try {
            //存入redis
            redisUtil.set(user.getUserId(),s,300);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResponseEntity.ok(BaseResult.body(phone, ResultType.BUSINESS_ERROR).withMessage("Redis服务出现错误"));
        }
        //发送短信
        SendSms sendSms = new SendSms();
        //短信渠道
        sendSms.setSmsChannel("1");
        //短信模板编码
        sendSms.setSmsTemplateEncoded("sendVerificationCode");
        //待发送手机号
        String[] strings = new String[]{phone};
        sendSms.setPhoneNumbers(strings);
        //短信模板变量
        Map<String,String> map = new HashMap<String,String>();
        map.put("verifycode",s);
        sendSms.setParamMap(map);
        BaseResult<?> baseResult = smsService.sendSms(sendSms);
        baseResult.setData(null);
        return ResponseEntity.ok(baseResult);
    }

    /**
     * 检查验证码 on 2019/5/17 11:25
     *
     * @return ResponseEntity<Object>
     */
    @ApiOperation(value = "检查验证码", httpMethod = "GET", produces = "application/json", response = ResponseEntity.class)
    @ResponseBody
    @GetMapping(value = "inspectVerificationCode")
    public ResponseEntity<Object> inspectVerificationCode(@ApiParam(value = "验证码", name = "code") @RequestParam(defaultValue = "")String code) {
        if(code == null || "".equals(code.trim())){
            return ResponseEntity.ok(BaseResult.body(code, ResultType.BUSINESS_ERROR).withMessage("验证码为空"));
        }
        IAccountUser user = UserUtils.getUser();
        if(user.getUserId() == null){
            return ResponseEntity.ok(BaseResult.body(code, ResultType.BUSINESS_ERROR).withMessage("获取不到当前用户"));
        }
        JSONObject object = getCode(user.getUserId());
        if(!object.getBoolean("state")){
            return ResponseEntity.ok(BaseResult.body(false, ResultType.BUSINESS_ERROR).withMessage(object.getString("message")));
        }
        if(object.getString("data").equals(code)){
            //删除验证码
            deleteCode(user.getUserId());
            return ResponseEntity.ok(BaseResult.body(true, ResultType.BUSINESS_SUCCESS).withMessage("验证码验证成功"));
        }else{
            return ResponseEntity.ok(BaseResult.body(false, ResultType.BUSINESS_ERROR).withMessage("验证码不正确"));
        }
    }

    /**
     * 修改手机号 on 2019/5/17 11:25
     *
     * @return ResponseEntity<Object>
     */
    @ApiOperation(value = "修改手机号", httpMethod = "POST", produces = "application/json", response = VerificationCodePojo.class)
    @ResponseBody
    @PostMapping(value = "updatePhone")
    public ResponseEntity<Object> updatePhone(@RequestBody VerificationCodePojo codePojo) {
        if(codePojo.getLoginPassword() == null || "".equals(codePojo.getLoginPassword().trim())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("登录密码为空"));
        }
        if(codePojo.getNewPhone() == null || "".equals(codePojo.getNewPhone().trim())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("新手机号为空"));
        }
        if(codePojo.getVerificationCode() == null || "".equals(codePojo.getVerificationCode().trim())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("验证码为空"));
        }
        IAccountUser user = UserUtils.getUser();
        if(user.getUserId() == null){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("获取不到当前用户"));
        }
        if(user.getPassword() == null){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("获取不到当前用户密码"));
        }
        //校验密码
        try {
            if(!MD5.md5(codePojo.getLoginPassword()).equals(user.getPassword())){
                return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("密码不正确"));
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("密码校验错误"));
        }
        //校验验证码
        JSONObject object = getCode(user.getUserId());
        if(!object.getBoolean("state")){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage(object.getString("message")));
        }
        if(!object.getString("data").equals(codePojo.getVerificationCode())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("验证码不正确"));
        }
        JSONObject jsonObject = UserUtils.updatePhone(user.getUserId(),codePojo.getNewPhone());
        if(jsonObject == null){
            jsonObject = new JSONObject();
            jsonObject.put("success",false);
            jsonObject.put("message","更新过程中出现错误");
        }
        if(jsonObject.getBoolean("success")){
            //删除验证码
            deleteCode(user.getUserId());
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_SUCCESS));
        }else {
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage(jsonObject.getString("message")));
        }
    }

    /**
     * 修改邮箱 on 2019/5/17 11:25
     *
     * @return ResponseEntity<Object>
     */
    @ApiOperation(value = "修改邮箱", httpMethod = "POST", produces = "application/json", response = VerificationCodePojo.class)
    @ResponseBody
    @PostMapping(value = "updateMail")
    public ResponseEntity<Object> updateMail(@RequestBody VerificationCodePojo codePojo) {
        if(codePojo.getPhone() == null || "".equals(codePojo.getPhone().trim())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("手机号为空"));
        }
        if(codePojo.getVerificationCode() == null || "".equals(codePojo.getVerificationCode().trim())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("验证码为空"));
        }
        if(codePojo.getNewMail() == null || "".equals(codePojo.getNewMail().trim())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("新邮箱为空"));
        }
        IAccountUser user = UserUtils.getUser();
        if(user.getUserId() == null){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("获取不到当前用户"));
        }
        if(user.getMobile() == null || "".equals(user.getMobile().trim())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("获取不到当前用户手机号"));
        }
        if(!user.getMobile().equals(codePojo.getPhone())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("手机号不正确"));
        }
        //校验验证码
        JSONObject object = getCode(user.getUserId());
        if(!object.getBoolean("state")){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage(object.getString("message")));
        }
        if(!object.getString("data").equals(codePojo.getVerificationCode())){
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage("验证码不正确"));
        }
        JSONObject jsonObject = UserUtils.updateMail(user.getUserId(),codePojo.getNewMail());
        if(jsonObject == null){
            jsonObject = new JSONObject();
            jsonObject.put("success",false);
            jsonObject.put("message","更新过程中出现错误");
        }
        if(jsonObject.getBoolean("success")){
            //删除验证码
            deleteCode(user.getUserId());
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_SUCCESS));
        }else{
            return ResponseEntity.ok(BaseResult.body(codePojo, ResultType.BUSINESS_ERROR).withMessage(jsonObject.getString("message")));
        }
    }

    /**
      * 从redis获取验证码 on 2019/5/17 16:32
      *
      * @param userId userId
      * @return JSONObject
      */
    private JSONObject getCode(String userId){
        JSONObject object = new JSONObject();
        String s = "";
        try {
            Object o = redisUtil.get(userId);
            if(o == null){
                object.put("state",false);
                object.put("message","验证码已超时");
                return object;
            }
            s = o.toString();
        }catch (Exception e){
            logger.error(e.getMessage());
            object.put("state",false);
            object.put("message","Redis服务出现错误");
            return object;
        }
        object.put("state",true);
        object.put("data",s);
        return object;
    }

    private boolean deleteCode(String userId){
        try {
            redisUtil.delete(userId);
        }catch (Exception e){
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }
}